#    Supsta
#    Copyright (c) 2014 Sebastian Dufner
#
#    This file is part of Supsta.
#
#    Supsta is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Supsta is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

require 'tempfile'

require 'supsta/gimp/image'

module Supsta
  module Gimp
    class Application

      def initialize
        @nvars = 0
        @script = ''
      end

      attr_reader :script

      def new_var
        "var#{@nvars += 1}"
      end

      def run
        tmp = Tempfile.new('supsta.scm')
        tmp.write script
        tmp.close

        fail 'Command exeuction failed. Do you have the GIMP installed?' if
          system("gimp-console -nb \"(load \\\"#{tmp.path}\\\")(gimp-quit 0)\"")
              .nil?

        tmp.unlink

        @nvars = 0
        @script = ''

        nil
      end
      alias_method :execute, :run

      def message(*args)
        s = ''
        args.each do |arg|
          s.concat '(gimp-message '
          s.concat "\"#{arg.to_s.gsub(/\\/, '\\\\').gsub(/"/, '\"')}\")\n"
        end

        @script.concat s

        self
      end
      alias_method :puts, :message

      def load_image(file)
        image = "image#{@nvars += 1}"
        file = file.gsub(/\\/, '\\\\').gsub(/"/, '\"')

        s =  "(define #{image} (car(gimp-file-load RUN-NONINTERACTIVE "
        s.concat "\"#{file}\" \"#{file}\")))\n"

        @script.concat s

        Image.new(self, image).set_profile_rgb
      end

      def new_image(width, height)
        image = "image#{@nvars += 1}"
        fail RangeError, "image width out of range: #{width}" unless
          (1..262144).include? width
        fail RangeError, "image height out of range: #{height}" unless
          (1..262144).include? height

        s = "(define #{image} (car(gimp-image-new #{width} #{height} 0)))"
        s.concat "(gimp-image-insert-layer #{image} (car(gimp-layer-new "
        s.concat "#{image} #{width} #{height} 1 \"background\" 100 0)) 0 -1"
        s.concat ")\n"
        @script.concat s

        Image.new(self, image).set_profile_rgb
      end

      def set_foreground(r, g, b)
        @script.concat "(gimp-context-set-foreground '(#{r} #{g} #{b}))"

        self
      end

    end
  end
end
